﻿// helper functions for different tasks

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

var serializeObjectToUrlParameters = function (obj) {
    var str = [];
    for (var p in obj)
        if (obj.hasOwnProperty(p) && obj[p] && obj[p] != '') {
            str.push(encodeURIComponent(p.toLowerCase()) + "=" + encodeURIComponent(obj[p]));
        }
    return str.join("&");
};

function LimitLength(str, len) {
    if (typeof str === 'undefined') {
        return '';
    }
    if (str == null) {
        return '';
    }
    if (str.length > len) {
        str = str.substring(0, len - 3) + '...';
    }
    return str;
}

function BeutifyNumber(num) {
    if (num > 1000) {
        var upperpart = Math.floor(num / 1000);
        var lowerpart = (num - upperpart * 1000)+'';
        while (lowerpart.length < 3) lowerpart = '0' + lowerpart;
        num = upperpart + ' ' + lowerpart;
    }
    return num;
}

function ShortNumber(num) {
    if (num < 100000) {
        return BeutifyNumber(num);
    }
    else if (num < 1000000) {
        return (Math.floor(num / 1000) + 'k');
    }
    else {
        return (Math.floor(num / 100000) / 10 + 'M');
    }
}


function jsonValidationPrepare(formId, successCallback, params) {
    $('form[id="' + formId + '"]').submit(function () {

        var button = $('form[id="' + formId + '"] :submit');
        if (button) {
            button.button('loading');
        }

        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success: function (response) {

                try {
                    var json = $.parseJSON(response);
                }
                catch (exception) {
                    alert(exception);
                    return;
                }

                successCallback(json, params);
            },
            complete: function () {
                if (button) {
                    button.button('reset');
                }
            }
        });
        return false;
    });
}

//json: parsed bimjsonvalidationresponse
//callback: function with 2 parameter: globalErrors, fieldErrors
//elementId: optional, if exists inputs will be searched only inside the html element
function jsonValidationProcessErrors(json, callback, elementId) {

    var globalErrors = [];
    var fieldErrors = [];

    $.each(json.Errors, function (key, value) {

        if (key != '') {

            var errorObj = new Object();
            errorObj[key] = value;
            fieldErrors.push(errorObj);

            var replaced = key.replace(/(\[|\]|\.)/g, '\\$1');
            var input = elementId ? $(':input[id="' + replaced + '"]', '#' + elementId) : $(':input[id="' + replaced + '"]');

            if (input.length > 0) { //if input exist in dom
                //do nothing yet
            } else {
                input = elementId ? $(':input[name="' + replaced + '"]', '#' + elementId) : $(':input[name="' + replaced + '"]');
                if (input.length > 0) { //if input exist in dom
                    //do nothing yet
                } else {
                    //add all error to the global errors
                    $.each(value, function(index2, value2) {
                        globalErrors.push(value2);
                    });
                }
            }

        } else {

            $.each(value, function (index2, value2) {
                globalErrors.push(value2);
            });

        }
    });

    callback(globalErrors, fieldErrors);

}

//Converts the given validation message container (e.g: json.Errors, json.Warnings, json.Messages) to 1D array of string.
function getAllMessageAsArrayOfString(messageContainer) {

    var result = [];

    if (messageContainer) {
        $.each(messageContainer, function (index, value) {
            $.each(value, function (index2, value2) {
                result.push(value2);
            });
        });
    }

    return result;

};


var countDown = function (onTick, onZero) {

    var t, count;
    var countdown = function () {

        // starts countdown
        if (onTick) {
            onTick(count);
        }

        if (count == 0) {
            // time is up
            if (onZero) {
                onZero();
            }

        } else {
            count--;
            t = setTimeout(countdown, 1000);
        }
    };

    return {
        start: function (seconds) {
            count = seconds;
            countdown();
        },
        pause: function() {
            clearTimeout(t);
        },
        resume: function() {
            countdown();
        }
    };

};